package com.example.myapp.Activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.myapp.ADO.ActivityManager;
import com.example.myapp.ADO.MyDialog;
import com.example.myapp.ADO.WX_Posts_Adapter;
import com.example.myapp.Listviewloading.MyFooterAdapter;
import com.example.myapp.Listviewloading.MyHeaderAdapter;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Article;
import com.example.myapp.Model.Fensi;
import com.example.myapp.Model.User;
import com.example.myapp.R;
import com.sak.ultilviewlib.UltimateRefreshView;
import com.sak.ultilviewlib.interfaces.OnFooterRefreshListener;
import com.sak.ultilviewlib.interfaces.OnHeaderRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import de.hdodenhof.circleimageview.CircleImageView;

public class Friendshome extends AppCompatActivity {
    private ImageView friendhome_back;
    private TextView friendhome_username;
    private TextView friendhome_jianjie;
    private Button friendhome_sixin;
    private TextView friendhome_count1;
    private  List<String> gzlist=new ArrayList<>();//关注
    private CircleImageView friendhome_head_image;
    private  String Userid;
    private String  iconUrl;
   private String  chatEnter;
    private String Username;
    private int p4 = R.id.settings_tab;
    private List<String> listarr = new ArrayList<>();
    private ShapeLoadingDialog shapeLoadingDialog;
    private TextView friendhome_guanzhu;


    private UltimateRefreshView mUltimateRefreshView;
    private int page = 0;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
    private String updatatime="";
    private RecyclerView recyclerView;
    private WX_Posts_Adapter adapter;
    private List<Article> postsList = new ArrayList<>();
    //开启异步线程
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: {
                    initguanzhu();
                    queryALLPost(Userid);
                } break;
                case 3: {
                    friendhome_guanzhu.setText("关注");
                    gzlist.remove(Userid);
                    friendhome_guanzhu.setTextColor(Color.parseColor("#FF5722"));//橘色
                    clearFriend(Userid);//取消关注
                } break;
            }
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityManager.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        ActivityManager.getInstance().addActivity(this);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //隐藏标题栏
        setContentView(R.layout.friends_home);
        friendhome_back = findViewById(R.id.friendhome_back);
        friendhome_username = findViewById(R.id.friendhome_username);
        friendhome_head_image = findViewById(R.id.friendhome_head_image);
        friendhome_jianjie = findViewById(R.id.friendhome_jianjie);
        friendhome_sixin = findViewById(R.id.friendhome_sixin);
        friendhome_guanzhu  = findViewById(R.id.friendhome_guanzhu);
        Intent intent =getIntent();
        Userid =intent.getStringExtra("userID");
        iconUrl =intent.getStringExtra("iconUrl");
        Username =intent.getStringExtra("userName");
        chatEnter =intent.getStringExtra("chatEnter");

        mUltimateRefreshView = (UltimateRefreshView)findViewById(R.id.refreshView);
        recyclerView= findViewById(R.id.mypostslistview);
        mUltimateRefreshView.setBaseHeaderAdapter(new MyHeaderAdapter(Friendshome.this));

        /**底部上拉加载*/
        mUltimateRefreshView.setBaseFooterAdapter(new MyFooterAdapter(Friendshome.this));


        mUltimateRefreshView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(UltimateRefreshView view) {

                mUltimateRefreshView.onHeaderRefreshComplete();
            }
        });


        /**底部上拉加载事件*/
        mUltimateRefreshView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
            @Override
            public void onFooterRefresh(UltimateRefreshView view) {
                page++;
                BmobQuery<Article> query = new BmobQuery<>();
                query.addWhereEqualTo("author", Userid);
                query.setSkip(page*5); // 忽略前10条数据（即第一页数据结果）
                query.setLimit(5); // 限制最多10条数据结果作为一页
                //包含作者信息
                query.include("author");
                query.order("-orderTime");
                query.findObjects(new FindListener<Article>() {
                    @Override
                    public void done(List<Article> object, BmobException e) {
                        if (e == null) {
                            if (object.size()>0){
                                postsList.addAll(object);
                                adapter.notifyDataSetChanged();
                                mUltimateRefreshView.onFooterRefreshComplete();
                            }else {
                                mUltimateRefreshView.onFooterRefreshComplete();
                            }
                        } else {
                            Log.e("aaaa","查询我的动态失败"+ e.getMessage());
                            mUltimateRefreshView.onFooterRefreshComplete();
                        }
                    }

                });



            }
        });

        Message message = new Message();
        message.what = 0;
        handler.sendMessage(message);
        friendhome_username.setText(Username);
        friendhome_jianjie.setText(intent.getStringExtra("jianJie"));
        Glide.with(Friendshome.this).load(iconUrl).into(friendhome_head_image);// CircleImageView.显示网络图片特殊方法


        friendhome_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(chatEnter!=null){
                    Intent intent = new Intent(Friendshome.this, Main.class);
                    intent.putExtra("page", R.id.contact_tab);//打开主页
                    startActivity(intent);
                    finish();
                }
                finish();
            }
        });
        friendhome_sixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Friendshome.this,VolleyChat.class);
                intent.putExtra("userID",Userid);
                intent.putExtra("iconUrl",iconUrl);
                intent.putExtra("userName",Username);
                intent.putExtra("isUserPagecome","friend");
                startActivity(intent);
            }
        });


        friendhome_guanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否已经关注
                if(friendhome_guanzhu.getText().toString().equals("关注")){
                    friendhome_guanzhu.setTextColor(Color.parseColor("#CCCCCC"));//橘色
                    friendhome_guanzhu.setText("已关注");
                    gzlist.add(Userid);//保存到当前关注数据刷新用，因为后台来不及刷新
                    saveFriend(Userid);//添加好友关联
                }
                else if(friendhome_guanzhu.getText().toString().equals("已关注")){

                    View view = getLayoutInflater().inflate(R.layout.exit_dialog_layout, null);
                    MyDialog mMyDialog = new MyDialog(Friendshome.this, 0, 0, view, R.style.DialogTheme);
                    TextView exitall=  view.findViewById(R.id.exitall);
                    TextView dialog_title=  view.findViewById(R.id.dialog_title);
                    TextView exitback=  view.findViewById(R.id.exitback);
                    if (chatEnter!=null){
                        dialog_title.setText("取消关注后好友列表就会被关闭删掉，是否继续？");
                    }else {
                        dialog_title.setText("你确定取消关注吗？");
                    }

                    mMyDialog.setCancelable(true);
                    mMyDialog.show();
                    exitall.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            Message message = new Message();
                            message.what = 3;
                            handler.sendMessage(message);
                            mMyDialog.dismiss();
                        }
                    });//取消关注
                    exitback.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mMyDialog.dismiss();
                        }
                    });//退出程序



                }
//

            }
        });//关注按钮



    }


    //    输入需要查询被关注的用户有被我关注
    private void initguanzhu(){
        if (BmobUser.isLogin()) {
            BmobQuery<User> query = new BmobQuery<User>();
            // 用此方式可以构造一个BmobPointer对象。只需要设置objectId就行
            User user = BmobUser.getCurrentUser(User.class);//查自己
            query.addWhereRelatedTo("friend", new BmobPointer(user));
            //包含作者信息
            query.include("user,author,article");
            query.findObjects(new FindListener<User>() {
                @Override
                public void done(List<User> object, BmobException e) {
                    if (e == null) {
                        Log.w("aaaa", "详情页面关注个数"+object.size());
                        for (int i=0;i<object.size();i++){
                            gzlist.add(object.get(i).getObjectId());
                        }
                        /**初始化关注*/
                        if (gzlist.contains(Userid)){
                            friendhome_guanzhu.setText("已关注");
                            Log.w("aaaa","当前用户"+BmobUser.getCurrentUser(User.class).getObjectId());
                            friendhome_guanzhu.setTextColor(Color.parseColor("#CCCCCC"));//已经关注的颜色
                        }


                    } else {
                        Log.e("aaaa","查询好友关注"+ e.getMessage());
                    }
                }
            });
        } else {
            Log.w("aaaa", "请先登录！");
        }
    }


    /** 添加多对多好友*/
    //填写被当前用户要关注的用户id
    private void saveFriend(String userObjId) {
        openLoading();
        if (BmobUser.isLogin()) {

            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            User user1 = new User();//创建被关注用户并且给上Id
            user1.setObjectId(userObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.add(user1);//装进去当前用户;
            user.setFriend(relation);
            user.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "添加好友成功");
                        closeLoading();
                        saveFensi(userObjId);
                    } else {
                        Log.i("aaaa", "添加好友失败：" + e.getMessage());
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }

    /** 删除多对多*/
    //填写被当前用户要关注的用户id
    private void clearFriend(String userObjId) {
        openLoading();
        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            User user1 = new User();//创建被关注用户并且给上Id
            user1.setObjectId(userObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.remove(user1);//装进去当前用户;
            user.setFriend(relation);
            user.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "取消关注成功");
                        //     notifyDataSetChanged();
                        closeLoading();
                        clearFensi(userObjId);
                    } else {
                        Log.i("aaaa", "取消关注失败：" + e.getMessage());
                        closeLoading();
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }



    /**添加一对多粉丝*/
    private void saveFensi(String userID) {
        User user = new User();
        user.setObjectId(userID);//测试文本1的文章id
        final Fensi fensi = new Fensi();
        fensi.setUser(user);
        fensi.setFensi(BmobUser.getCurrentUser(User.class));
        fensi.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "添加粉丝成功！");
                } else {
                    Log.w("aaaa", "添加粉丝成功失败：" + e.getMessage());
                }
            }

        });
    }
    /**删除一对多粉丝*/
    private  void clearFensi(String userID){
        BmobQuery<Fensi> eq1 = new BmobQuery<>();
        eq1.addWhereEqualTo("user",userID);
        BmobQuery<Fensi> eq2 = new BmobQuery<>();
        eq2.addWhereEqualTo("fensi", BmobUser.getCurrentUser(User.class).getObjectId());
        List<BmobQuery<Fensi>> queries = new ArrayList<BmobQuery<Fensi>>();
        queries.add(eq1);
        queries.add(eq2);
        //查询符合整个and条件的人
        BmobQuery<Fensi> addquery = new BmobQuery<Fensi>();
        addquery.and(queries);
        addquery.findObjects(new FindListener<Fensi>() {
            @Override
            public void done(List<Fensi> object, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "查询粉丝成功："+object.get(0).getObjectId() );
                    Fensi p2 = new Fensi();
                    p2.setObjectId(object.get(0).getObjectId());
                    p2.delete(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                Log.w("aaaa", "删除粉丝成功:"+p2.getUpdatedAt());
                            }else{
                                Log.w("aaaa", "删除粉丝失败：" + e.getMessage());
                            }
                        }
                    });

                } else {
                    Log.w("aaaa", "查询粉丝失败："+e.getMessage() );
                }
            }
        });

    }




    @Override
    public void onBackPressed() {
        //此处写退向后台的处理
        finish();
        Log.w("aaaa", "我点击返回键！");
    }//手机返回键

    /**
     * 查询我说有关注
     */
    private void queryALLguanzhu(){
        if (BmobUser.isLogin()) {
            BmobQuery<User> query = new BmobQuery<User>();
            // 用此方式可以构造一个BmobPointer对象。只需要设置objectId就行
            User user = BmobUser.getCurrentUser(User.class);//查自己
            query.addWhereRelatedTo("friend", new BmobPointer(user));
            //包含作者信息
            query.include("user,author,article");
            query.findObjects(new FindListener<User>() {
                @Override
                public void done(List<User> object, BmobException e) {
                    if (e == null) {
                        Log.w("aaaa", "我的关注个数"+object.size());
                        for (int i=0;i<object.size();i++){
                            listarr.add(object.get(i).getObjectId());
                        }
                    } else {
                        Log.e("aaaa","查询好友关注"+ e.getMessage());
                    }
                }
            });
        } else {
            Log.w("aaaa", "请先登录！");
        }
    }

    /**
     * 查询一对多，我的所有动态1}
     */
    private void queryALLPost(String userid) {

        if (BmobUser.isLogin()) {
            // 用此方式可以构造一个BmobPointer对象。只需要设置objectId就行
            BmobQuery<Article> query = new BmobQuery<>();
            query.addWhereEqualTo("author",userid);
            query.setLimit(8); // 限制最多10条数据结果作为一页
            //包含作者信息
            query.include("author");
            query.order("-orderTime");
            query.findObjects(new FindListener<Article>() {
                @Override
                public void done(List<Article> object, BmobException e) {
                    if (e == null) {
                        Log.w("aaaa", "我的动态页面" + object.size());
                        postsList=object;
                        if(postsList.size()>0){
                            LinearLayoutManager layoutManager = new LinearLayoutManager(Friendshome.this);//正常listview
                            recyclerView.setLayoutManager(layoutManager);
                            recyclerView.setItemViewCacheSize(500);
                            adapter =new WX_Posts_Adapter(Friendshome.this, postsList);
                            recyclerView.setAdapter(adapter);
                            Log.w("bmob", "成功找到我发布的帖子！"+object.size());
                        }



                    } else {
                        Log.e("aaaa", "查询我的动态失败" + e.getMessage());
                    }
                }

            });
        } else {
            Log.w("aaaa", "请先登录！");
        }
    }

    //网络加载
    private void openLoading() {
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(Friendshome.this)
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }

    //关闭网络加载
    private void closeLoading() {
        shapeLoadingDialog.dismiss();
    }
}